{% extends "base.html" %}

{% block title %}系统设置 - IT课程数据分析系统{% endblock %}

{% block extra_css %}
<style>
    .settings-container {
        max-width: 900px;
        margin: 0 auto;
    }
    
    .settings-tabs {
        display: flex;
        gap: 1rem;
        margin-bottom: 2rem;
        border-bottom: 2px solid #e0e0e0;
    }
    
    .tab {
        padding: 1rem 1.5rem;
        cursor: pointer;
        border-bottom: 3px solid transparent;
        transition: all 0.3s;
        font-weight: 500;
    }
    
    .tab:hover {
        background: #f8f9fa;
    }
    
    .tab.active {
        border-bottom-color: #3498db;
        color: #3498db;
    }
    
    .tab-content {
        display: none;
    }
    
    .tab-content.active {
        display: block;
    }
    
    .setting-group {
        margin-bottom: 2rem;
    }
    
    .setting-group h3 {
        color: #2c3e50;
        margin-bottom: 1rem;
        padding-bottom: 0.5rem;
        border-bottom: 2px solid #e0e0e0;
    }
    
    .setting-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 1rem;
        background: #f8f9fa;
        border-radius: 8px;
        margin-bottom: 1rem;
    }
    
    .setting-item label {
        font-weight: 500;
        color: #2c3e50;
    }
    
    .setting-item .description {
        font-size: 0.85rem;
        color: #7f8c8d;
        margin-top: 0.25rem;
    }
    
    .setting-item input[type="text"],
    .setting-item input[type="number"],
    .setting-item input[type="email"],
    .setting-item select {
        padding: 0.5rem;
        border: 1px solid #e0e0e0;
        border-radius: 4px;
        min-width: 200px;
    }
    
    .toggle-switch {
        position: relative;
        width: 50px;
        height: 26px;
    }
    
    .toggle-switch input {
        opacity: 0;
        width: 0;
        height: 0;
    }
    
    .slider {
        position: absolute;
        cursor: pointer;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background-color: #ccc;
        transition: .4s;
        border-radius: 26px;
    }
    
    .slider:before {
        position: absolute;
        content: "";
        height: 18px;
        width: 18px;
        left: 4px;
        bottom: 4px;
        background-color: white;
        transition: .4s;
        border-radius: 50%;
    }
    
    input:checked + .slider {
        background-color: #2ecc71;
    }
    
    input:checked + .slider:before {
        transform: translateX(24px);
    }
    
    .status-badge {
        display: inline-block;
        padding: 0.25rem 0.75rem;
        border-radius: 12px;
        font-size: 0.85rem;
        font-weight: 600;
    }
    
    .status-online {
        background: #d4edda;
        color: #155724;
    }
    
    .status-offline {
        background: #f8d7da;
        color: #721c24;
    }
    
    .system-info-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 1rem;
        margin-bottom: 2rem;
    }
    
    .info-card {
        background: #f8f9fa;
        padding: 1rem;
        border-radius: 8px;
        border-left: 4px solid #3498db;
    }
    
    .info-card .label {
        font-size: 0.85rem;
        color: #7f8c8d;
        margin-bottom: 0.5rem;
    }
    
    .info-card .value {
        font-size: 1.25rem;
        font-weight: 600;
        color: #2c3e50;
    }
    
    .logs-table {
        width: 100%;
        border-collapse: collapse;
        font-size: 0.9rem;
    }
    
    .logs-table th,
    .logs-table td {
        padding: 0.75rem;
        text-align: left;
        border-bottom: 1px solid #e0e0e0;
    }
    
    .logs-table th {
        background: #f8f9fa;
        font-weight: 600;
    }
    
    .log-level {
        display: inline-block;
        padding: 0.25rem 0.5rem;
        border-radius: 4px;
        font-size: 0.8rem;
        font-weight: 600;
    }
    
    .log-INFO {
        background: #d1ecf1;
        color: #0c5460;
    }
    
    .log-WARNING {
        background: #fff3cd;
        color: #856404;
    }
    
    .log-ERROR {
        background: #f8d7da;
        color: #721c24;
    }
</style>
{% endblock %}

{% block content %}
<div class="settings-container">
    <h2 style="margin-bottom:1.5rem;">系统设置</h2>
    
    <div class="settings-tabs">
        <div class="tab active" onclick="switchTab('general')">基本设置</div>
        <div class="tab" onclick="switchTab('system')">系统信息</div>
        <div class="tab" onclick="switchTab('logs')">系统日志</div>
        <div class="tab" onclick="switchTab('advanced')">高级设置</div>
    </div>
    
    <!-- 基本设置 -->
    <div id="general-tab" class="tab-content active">
        <div class="card">
            <div class="setting-group">
                <h3>站点信息</h3>
                
                <div class="setting-item">
                    <div>
                        <label>站点名称</label>
                        <div class="description">系统显示的名称</div>
                    </div>
                    <input type="text" id="site-name" value="">
                </div>
                
                <div class="setting-item">
                    <div>
                        <label>站点描述</label>
                        <div class="description">系统的简短描述</div>
                    </div>
                    <input type="text" id="site-description" value="">
                </div>
                
                <div class="setting-item">
                    <div>
                        <label>系统版本</label>
                        <div class="description">当前系统版本号</div>
                    </div>
                    <input type="text" id="version" value="" readonly style="background:#e9ecef;">
                </div>
            </div>
            
            <div class="setting-group">
                <h3>功能开关</h3>
                
                <div class="setting-item">
                    <div>
                        <label>允许用户注册</label>
                        <div class="description">是否允许新用户自主注册</div>
                    </div>
                    <label class="toggle-switch">
                        <input type="checkbox" id="enable-registration">
                        <span class="slider"></span>
                    </label>
                </div>
                
                <div class="setting-item">
                    <div>
                        <label>启用数据分析</label>
                        <div class="description">是否启用数据统计分析功能</div>
                    </div>
                    <label class="toggle-switch">
                        <input type="checkbox" id="enable-analytics">
                        <span class="slider"></span>
                    </label>
                </div>
                
                <div class="setting-item">
                    <div>
                        <label>维护模式</label>
                        <div class="description">开启后系统将暂停服务</div>
                    </div>
                    <label class="toggle-switch">
                        <input type="checkbox" id="maintenance-mode">
                        <span class="slider"></span>
                    </label>
                </div>
                
                <div class="setting-item">
                    <div>
                        <label>启用批量导入</label>
                        <div class="description">是否启用多文件批量导入功能</div>
                    </div>
                    <label class="toggle-switch">
                        <input type="checkbox" id="enable-batch-import" checked>
                        <span class="slider"></span>
                    </label>
                </div>
            </div>
            
            <div class="setting-group">
                <h3>上传设置</h3>
                
                <div class="setting-item">
                    <div>
                        <label>最大文件大小</label>
                        <div class="description">文件上传大小限制（MB）</div>
                    </div>
                    <input type="number" id="max-file-size" min="1" max="100" value="">
                </div>
                
                <div class="setting-item">
                    <div>
                        <label>每页显示数量</label>
                        <div class="description">列表分页每页显示条目数</div>
                    </div>
                    <input type="number" id="items-per-page" min="10" max="100" value="">
                </div>
            </div>
            
            <div class="setting-group">
                <h3>批量导入设置</h3>
                
                <div class="setting-item">
                    <div>
                        <label>最大文件数量</label>
                        <div class="description">单次批量导入的最大文件数量</div>
                    </div>
                    <input type="number" id="max-batch-files" min="1" max="50" value="10">
                </div>
                
                <div class="setting-item">
                    <div>
                        <label>批量总大小</label>
                        <div class="description">批量导入文件的总大小限制（MB）</div>
                    </div>
                    <input type="number" id="max-batch-size" min="10" max="500" value="100">
                </div>
                
                <div class="setting-item">
                    <div>
                        <label>并发处理数</label>
                        <div class="description">同时处理的文件数量（高值可能影响性能）</div>
                    </div>
                    <input type="number" id="concurrent-processing" min="1" max="10" value="3">
                </div>
            </div>
            
            <div style="display:flex;gap:1rem;justify-content:flex-end;">
                <button class="btn btn-primary" onclick="saveSettings()">保存设置</button>
                <button class="btn btn-danger" onclick="resetSettings()">恢复默认</button>
            </div>
        </div>
    </div>
    
    <!-- 系统信息 -->
    <div id="system-tab" class="tab-content">
        <div class="card">
            <h3 style="margin-bottom:1rem;">系统状态</h3>
            
            <div class="system-info-grid" id="system-stats">
                <div class="info-card">
                    <div class="label">总用户数</div>
                    <div class="value" id="stat-users">-</div>
                </div>
                <div class="info-card">
                    <div class="label">学生数量</div>
                    <div class="value" id="stat-students">-</div>
                </div>
                <div class="info-card">
                    <div class="label">教师数量</div>
                    <div class="value" id="stat-teachers">-</div>
                </div>
                <div class="info-card">
                    <div class="label">课程数量</div>
                    <div class="value" id="stat-courses">-</div>
                </div>
                <div class="info-card">
                    <div class="label">选课记录</div>
                    <div class="value" id="stat-enrollments">-</div>
                </div>
                <div class="info-card">
                    <div class="label">系统日志</div>
                    <div class="value" id="stat-logs">-</div>
                </div>
            </div>
            
            <h3 style="margin-bottom:1rem;margin-top:2rem;">服务器信息</h3>
            
            <div class="system-info-grid" id="server-info">
                <div class="info-card">
                    <div class="label">操作系统</div>
                    <div class="value" id="info-platform" style="font-size:1rem;">-</div>
                </div>
                <div class="info-card">
                    <div class="label">Python版本</div>
                    <div class="value" id="info-python" style="font-size:1rem;">-</div>
                </div>
                <div class="info-card">
                    <div class="label">CPU使用率</div>
                    <div class="value" id="info-cpu">-</div>
                </div>
                <div class="info-card">
                    <div class="label">内存使用率</div>
                    <div class="value" id="info-memory">-</div>
                </div>
            </div>
            
            <div style="margin-top:2rem;text-align:right;">
                <button class="btn btn-primary" onclick="loadSystemStatus()">刷新</button>
                <button class="btn btn-primary" onclick="backupDatabase()">备份数据库</button>
            </div>
        </div>
    </div>
    
    <!-- 系统日志 -->
    <div id="logs-tab" class="tab-content">
        <div class="card">
            <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:1rem;">
                <h3>系统日志</h3>
                <div>
                    <select id="log-level-filter" onchange="loadLogs()" style="padding:0.5rem;margin-right:0.5rem;">
                        <option value="">全部级别</option>
                        <option value="INFO">INFO</option>
                        <option value="WARNING">WARNING</option>
                        <option value="ERROR">ERROR</option>
                    </select>
                    <button class="btn btn-danger" onclick="clearLogs()">清理旧日志</button>
                </div>
            </div>
            
            <div style="max-height:600px;overflow-y:auto;">
                <table class="logs-table">
                    <thead>
                        <tr>
                            <th>时间</th>
                            <th>级别</th>
                            <th>操作</th>
                            <th>用户</th>
                            <th>IP地址</th>
                            <th>消息</th>
                        </tr>
                    </thead>
                    <tbody id="logs-tbody">
                        <tr>
                            <td colspan="6" style="text-align:center;color:#7f8c8d;">加载中...</td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    
    <!-- 高级设置 -->
    <div id="advanced-tab" class="tab-content">
        <div class="card">
            <div class="setting-group">
                <h3>性能优化</h3>
                
                <div class="setting-item">
                    <div>
                        <label>启用缓存</label>
                        <div class="description">启用数据缓存以提升性能</div>
                    </div>
                    <label class="toggle-switch">
                        <input type="checkbox" id="enable-cache">
                        <span class="slider"></span>
                    </label>
                </div>
                
                <div class="setting-item">
                    <div>
                        <label>缓存超时时间</label>
                        <div class="description">缓存数据的有效期（秒）</div>
                    </div>
                    <input type="number" id="cache-timeout" min="60" max="3600" value="">
                </div>
                
                <div class="setting-item">
                    <div>
                        <label>会话超时时间</label>
                        <div class="description">用户会话的有效期（秒）</div>
                    </div>
                    <input type="number" id="session-timeout" min="300" max="86400" value="">
                </div>
            </div>
            
            <div style="display:flex;gap:1rem;justify-content:flex-end;">
                <button class="btn btn-primary" onclick="saveSettings()">保存设置</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    let currentSettings = {};
    
    function switchTab(tabName) {
        // 切换标签激活状态
        document.querySelectorAll('.tab').forEach(tab => {
            tab.classList.remove('active');
        });
        event.target.classList.add('active');
        
        // 切换内容显示
        document.querySelectorAll('.tab-content').forEach(content => {
            content.classList.remove('active');
        });
        document.getElementById(`${tabName}-tab`).classList.add('active');
        
        // 如果切换到系统信息标签，加载系统状态
        if (tabName === 'system') {
            loadSystemStatus();
        }
        
        // 如果切换到日志标签，加载日志
        if (tabName === 'logs') {
            loadLogs();
        }
    }
    
    async function loadSettings() {
        try {
            const data = await apiRequest('/settings');
            
            if (data.success) {
                currentSettings = data.data;
                
                // 填充表单
                document.getElementById('site-name').value = currentSettings.site_name || '';
                document.getElementById('site-description').value = currentSettings.site_description || '';
                document.getElementById('version').value = currentSettings.version || '1.0.0';
                document.getElementById('max-file-size').value = currentSettings.max_file_size || 16;
                document.getElementById('items-per-page').value = currentSettings.items_per_page || 20;
                document.getElementById('cache-timeout').value = currentSettings.cache_timeout || 300;
                document.getElementById('session-timeout').value = currentSettings.session_timeout || 3600;
                
                // 填充开关
                document.getElementById('enable-registration').checked = currentSettings.enable_registration || false;
                document.getElementById('enable-analytics').checked = currentSettings.enable_analytics !== false;
                document.getElementById('maintenance-mode').checked = currentSettings.maintenance_mode || false;
                document.getElementById('enable-cache').checked = currentSettings.enable_cache || false;
            }
        } catch (error) {
            showAlert('加载设置失败: ' + error.message, 'error');
        }
    }
    
    async function saveSettings() {
        try {
            const settings = {
                site_name: document.getElementById('site-name').value,
                site_description: document.getElementById('site-description').value,
                max_file_size: parseInt(document.getElementById('max-file-size').value),
                items_per_page: parseInt(document.getElementById('items-per-page').value),
                cache_timeout: parseInt(document.getElementById('cache-timeout').value),
                session_timeout: parseInt(document.getElementById('session-timeout').value),
                enable_registration: document.getElementById('enable-registration').checked,
                enable_analytics: document.getElementById('enable-analytics').checked,
                maintenance_mode: document.getElementById('maintenance-mode').checked,
                enable_cache: document.getElementById('enable-cache').checked
            };
            
            const data = await apiRequest('/settings', {
                method: 'PUT',
                body: JSON.stringify(settings)
            });
            
            if (data.success) {
                showAlert('设置已保存', 'success');
                loadSettings();
            }
        } catch (error) {
            showAlert('保存失败: ' + error.message, 'error');
        }
    }
    
    async function resetSettings() {
        if (!confirm('确定要恢复默认设置吗？')) {
            return;
        }
        
        try {
            const data = await apiRequest('/settings/reset', {
                method: 'POST'
            });
            
            if (data.success) {
                showAlert('已恢复默认设置', 'success');
                loadSettings();
            }
        } catch (error) {
            showAlert('重置失败: ' + error.message, 'error');
        }
    }
    
    async function loadSystemStatus() {
        try {
            const data = await apiRequest('/system/status');
            
            if (data.success) {
                const stats = data.data.statistics;
                const info = data.data.system_info;
                
                // 更新统计数据
                document.getElementById('stat-users').textContent = stats.total_users;
                document.getElementById('stat-students').textContent = stats.total_students;
                document.getElementById('stat-teachers').textContent = stats.total_teachers;
                document.getElementById('stat-courses').textContent = stats.total_courses;
                document.getElementById('stat-enrollments').textContent = stats.total_enrollments;
                document.getElementById('stat-logs').textContent = stats.total_logs;
                
                // 更新服务器信息
                document.getElementById('info-platform').textContent = info.platform || 'Unknown';
                document.getElementById('info-python').textContent = info.python_version || '-';
                document.getElementById('info-cpu').textContent = (info.cpu_percent || 0).toFixed(1) + '%';
                document.getElementById('info-memory').textContent = (info.memory_percent || 0).toFixed(1) + '%';
            }
        } catch (error) {
            showAlert('加载系统状态失败: ' + error.message, 'error');
        }
    }
    
    async function loadLogs() {
        try {
            const level = document.getElementById('log-level-filter').value;
            const url = level ? `/logs?level=${level}&per_page=100` : '/logs?per_page=100';
            
            const data = await apiRequest(url);
            
            if (data.success) {
                const tbody = document.getElementById('logs-tbody');
                
                if (data.data.length === 0) {
                    tbody.innerHTML = '<tr><td colspan="6" style="text-align:center;color:#7f8c8d;">暂无日志</td></tr>';
                    return;
                }
                
                tbody.innerHTML = data.data.map(log => `
                    <tr>
                        <td>${new Date(log.timestamp).toLocaleString()}</td>
                        <td><span class="log-level log-${log.level}">${log.level}</span></td>
                        <td>${log.action || '-'}</td>
                        <td>${log.user_id || '-'}</td>
                        <td>${log.ip_address || '-'}</td>
                        <td>${log.message || '-'}</td>
                    </tr>
                `).join('');
            }
        } catch (error) {
            console.error('加载日志失败:', error);
        }
    }
    
    async function clearLogs() {
        if (!confirm('确定要清理30天前的旧日志吗？')) {
            return;
        }
        
        try {
            const data = await apiRequest('/logs/clear', {
                method: 'POST'
            });
            
            if (data.success) {
                showAlert(data.message, 'success');
                loadLogs();
            }
        } catch (error) {
            showAlert('清理失败: ' + error.message, 'error');
        }
    }
    
    async function backupDatabase() {
        try {
            const data = await apiRequest('/database/backup', {
                method: 'POST'
            });
            
            if (data.success) {
                showAlert(data.message, 'success');
            }
        } catch (error) {
            showAlert('备份失败: ' + error.message, 'error');
        }
    }
    
    // 页面加载时执行
    window.addEventListener('DOMContentLoaded', () => {
        const userInfo = JSON.parse(localStorage.getItem('user_info') || '{}');
        if (userInfo.role !== 'admin') {
            showAlert('权限不足', 'error');
            setTimeout(() => window.location.href = '/', 2000);
            return;
        }
        
        loadSettings();
        
        // 初始化批量导入设置显示
        updateBatchImportVisibility();
        
        // 监听批量导入开关
        document.getElementById('enable-batch-import').addEventListener('change', updateBatchImportVisibility);
    });
    
    // 更新批量导入设置的显示状态
    function updateBatchImportVisibility() {
        const enableBatchImport = document.getElementById('enable-batch-import').checked;
        const batchSettings = document.querySelectorAll('#max-batch-files, #max-batch-size, #concurrent-processing');
        
        batchSettings.forEach(input => {
            input.disabled = !enableBatchImport;
            input.parentElement.style.opacity = enableBatchImport ? '1' : '0.5';
        });
    }
</script>
{% endblock %}







